import { Component, OnInit, Input, Output, EventEmitter, ViewChild } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
import * as moment from 'moment';

import { CudTableService } from 'app/public/serve/cud-table/cud-table.service';
import { HintsService } from '../../../../public/serve/hints/hints.service';
import { InitService } from '../../../../public/serve/init/init.service';
import { Service } from '../../../../server/server';

import { taskAddEimt } from "../../product-task-list";
import { appProductUrl } from '../../../product.url';
import { product } from '../../../product.data';
import {appSynonymUrl} from '../../../../synonym/synonym.url';

declare var $: any;

@Component({
    selector: 'app-product-indexing-task-list-add',
    templateUrl: './product-indexing-task-list-add.component.html'
})
export class ProductIndexingTaskListAddComponent implements OnInit {
    modalTitle: string = '';                            //弹窗标题
    taskData: any;                                      //任务数据
    type: string;                                       //类型(编辑任务, 新增任务<子任务,主任务>)
    taskId: string = '';
    @Output() onSubmit = new EventEmitter<void>();
    public taskProjectEmit: any;

    taskType: string;   //任务类型(0产品, 1内文)
    taskName: string;   //任务名称
    taskAssignPeoplesNames: Array<string> = [];         //标引人(数组)
    taskAssignUserNames = '';                           //标引人(字符串)
    taskAuditUserNames = '';                            //审核人
    templateNames = '';                             //模板名称
    templateIds = '';                             //模板id
    taskThemeWordNames: Array<string> = [];             //主题词表名称(数组)
    themeWordNames: string = '';                        //主题词表名称(字符串)
    taskThemeWordIds: Array<string> = [];               //主题词表Ids(数组)
    themeWordIds: string = '';                          //主题词Ids(字符串)
    description: string = '';                           //描述
    planCompleteDate: any;                              //预计完成时间
    planCheckDate: any;                                 //预计审核时间
    projectInfo = [];
    projectId : any = '';//项目id
    @ViewChild('addForm') formElement: HTMLFormElement;
    isEdit = false;

    constructor(
		private activatedRoute: ActivatedRoute,
        private server: Service,
        public initService: InitService,
        private request: CudTableService,
        private hintsService: HintsService) {
    }

    ngOnInit() {
        this.taskProjectEmit = this.server.taskProjectEmit.subscribe((value: any) => {
            this.projectInfo = [...value];
        });

		this.activatedRoute.queryParams.subscribe((p: Params) => {
			this.taskType = String(p['taskType']);
        });

        this.one = taskAddEimt.subscribe((value: any) => {
            if (value && value.type) {
                if(value.data.projectId != null && value.data.projectId != ''){
                    this.projectInfo = [{
                        projectId:value.data.projectId,
                        projectName:value.data.projectName
                    }];
                }

                this.planCompleteDate = new Date();
                this.planCheckDate = new Date();
                this.type = value.type;
                this.taskData = value.data;
                if (this.type === 'addChildTask') {
                    this.modalTitle = '新增子任务';
                    if (this.taskData.idxTaskThemeTableList && this.taskData.idxTaskThemeTableList.length > 0) {
                        this.taskData.idxTaskThemeTableList.forEach((obj, i) => {
                            this.taskThemeWordNames.push(obj['themeWordTableName']);
                            this.taskThemeWordIds.push(obj['themeTableId']);
                        });
                        this.themeWordNames = this.taskThemeWordNames.join(',');
                        this.themeWordIds = this.taskThemeWordIds.join(',');
                    }
                    this.templateNames = this.taskData.templateName;
                    this.templateIds = this.taskData.templateId;
                    this.isEdit = true;
                } else if (this.type === 'mainTask') {
                    this.modalTitle = '新增主任务';
                    this.templateIds = '';
                    this.isEdit = false;
                } else if (this.type === 'edit') {
                    this.templateNames = this.taskData.templateName;
                    this.templateIds = this.taskData.templateId;
                    this.projectId = this.taskData.projectId;
                    this.taskId = this.taskData.taskId;
                    this.modalTitle = `编辑任务`;
                    this.taskName = this.taskData.name;
                    this.description = this.taskData.description;
                    this.planCompleteDate = moment(this.taskData.planCompleteDate).format('YYYY-MM-DD');
                    this.planCheckDate = moment(this.taskData.planCheckDate).format('YYYY-MM-DD');
                    if (this.taskData.idxTaskAssignList && this.taskData.idxTaskAssignList.length > 0) {
                        this.taskData.idxTaskAssignList.forEach((obj, i) => {
                            this.taskAssignPeoplesNames.push(obj['taskAssignBy']);
                        });
                        this.taskAssignUserNames = this.taskAssignPeoplesNames.join(',');
                    }
                    if (this.taskData.taskCheckBy) {
                        this.taskAuditUserNames = this.taskData.taskCheckBy;
                    }
                    if (this.taskData.idxTaskThemeTableList && this.taskData.idxTaskThemeTableList.length > 0) {
                        this.taskData.idxTaskThemeTableList.forEach((obj, i) => {
                            this.taskThemeWordNames.push(obj['themeWordTableName']);
                            this.taskThemeWordIds.push(obj['themeTableId']);
                        });
                        this.themeWordNames = this.taskThemeWordNames.join(',');
                        this.themeWordIds = this.taskThemeWordIds.join(',');
                    }
                    //编辑子任务
                    if(this.taskData.parentId != 0){
                        //子任务
                        this.isEdit = true;
                    }else{
                        //主任务
                        //是否有资源
                        if(this.taskData.productCount > 0){
                            this.isEdit = true; //有资源就不能修改
                        }else{
                            this.isEdit = false;
                        }
                    }

                    //需要返回已选的模板信息(未写)
                    if (this.taskData.idxTaskTemplateList && this.taskData.idxTaskTemplateList.length > 0) {
                        this.taskData.idxTaskTemplateList.forEach((obj, i) => {
                            this.templateNames = obj['templateName'];
                            this.templateIds = obj['templateId'];
                        });
                    }
                } else if (this.type === 'detail') {
                    this.isEdit = false;
                    this.modalTitle = '查看主任务';
                    this.templateNames = this.taskData.templateName;
                    this.taskId = this.taskData.taskId;
                    this.taskName = this.taskData.name;
                    this.description = this.taskData.description;
                    this.planCompleteDate = moment(this.taskData.planCompleteDate).format('YYYY-MM-DD');
                    this.planCheckDate = moment(this.taskData.planCheckDate).format('YYYY-MM-DD');
                    if (this.taskData.idxTaskAssignList && this.taskData.idxTaskAssignList.length > 0) {
                        this.taskData.idxTaskAssignList.forEach((obj, i) => {
                            this.taskAssignPeoplesNames.push(obj['taskAssignBy']);
                        });
                        this.taskAssignUserNames = this.taskAssignPeoplesNames.join(',');
                    }
                    if (this.taskData.taskCheckBy) {
                        this.taskAuditUserNames = this.taskData.taskCheckBy;
                    }
                    if (this.taskData.idxTaskThemeTableList && this.taskData.idxTaskThemeTableList.length > 0) {
                        this.taskData.idxTaskThemeTableList.forEach((obj, i) => {
                            this.taskThemeWordNames.push(obj['themeWordTableName']);
                            this.taskThemeWordIds.push(obj['themeTableId']);
                        });
                        this.themeWordNames = this.taskThemeWordNames.join(',');
                        this.themeWordIds = this.taskThemeWordIds.join(',');
                    }
                }
            }
        });
    }

    //取消订阅
    public one: any;
    ngOnDestroy() {
        if (this.one) {
            this.one.unsubscribe();
        }
        if (this.taskProjectEmit) {
            this.taskProjectEmit.unsubscribe();
        }
    }

    clear() {
        this.formElement.reset();
        this.taskData = '';
        this.type = '';
        this.modalTitle = '';
        this.taskName = '';
        this.taskAssignPeoplesNames = [];
        this.taskAssignUserNames = '';
        this.taskAuditUserNames = '';
        this.taskThemeWordNames = [];
        this.themeWordNames = '';
        this.taskThemeWordIds = [];
        this.themeWordIds = '';
        this.description = '';
        this.taskId = '';
        this.planCompleteDate = '';
        this.planCheckDate = '';
        this.projectInfo = [];
    }


    /**
     * 验证是否可以为空
     * @param params 
     */
    isSubmitVal(){
        if(this.taskType == '2'){
            if(this.taskName && this.taskAssignUserNames && this.taskAuditUserNames && this.themeWordNames){
                return false;
            }else{
                return true;
            }
        }else{
            if(this.taskName && this.templateNames && this.taskAssignUserNames && this.taskAuditUserNames && this.themeWordNames && this.projectInfo.length > 0){
                return false;
            }else{
                return true;
            }
        }
        
    }

    /**
     * 新增提交
     * @param params 
     */
    _onSubmit(params: any) {
        params.token = product.retrieval.token;
        params.siteId = !this.taskData ? '0' : this.taskData.siteId;    //站点(根<新>任务为0,子任务与父任务站点一致,编辑任务与原来一致)
        params.taskType = this.taskType;                   //0产品, 1内文
        //params.taskStatus = !this.taskData ? '0' : this.taskData.taskStatus;    //0正常,1暂停(根<新>任务为0,子任务与父任务状态一致,编辑任务与原来一致)
        params.parentId = !this.taskData ? '0' : (this.type === 'addChildTask' ? this.taskData.taskId : this.taskData.parentId);       //父id,顶层为0(根<新>任务为0,子任务为父任务taskId,编辑任务与原来一致)
        params.arrParentId = !this.taskData || this.type === 'addChildTask' ? '0' : this.taskData.arrParentId;      //所有父id,逗号分割(需要判断)
        params.child = !this.taskData || this.type === 'addChildTask' ? '0' : this.taskData.child;          //是否存在子任务,0=不存在,1=存在
        params.listorder = !this.taskData || this.type === 'addChildTask' ? '' : this.taskData.listorder;
        //params.checkStatus = !this.taskData ? '0' : (this.type === 'addChildTask' ? '0' : this.taskData.checkStatus);   //审核状态,200=通过,0=未审,-1=审核未通过(根<新>任务为0,子任务为0,编辑任务与原来一致)    
        //params.submitStatus = !this.taskData ? '0' : (this.type === 'addChildTask' ? '0' : this.taskData.submitStatus);  //送审,0=未送审,1=已送审(根<新>任务为0,子任务为0,编辑任务与原来一致) 
        //params.completeDate = !this.taskData || this.type === 'addChildTask' ? '' : this.taskData.completeDate;   //预计完成时间
        params.createBy = !this.taskData || this.type === 'addChildTask' ? this.server.getuserName() : this.taskData.createBy;   //创建人(根<新>任务为当前登录用户id,子任务为当前用户id,编辑任务与原来一致)
        params.taskAssignBy = this.taskAssignPeoplesNames;     // 分配人,一个或多个(数组)
        params.taskCheckBy = this.taskAuditUserNames;           //审核人
        params.themeWordTableIds = this.taskThemeWordIds; //主题词,一个或多个(数组)
        params.planCompleteDate = moment(params.planCompleteDate).format('YYYY-MM-DD');
        params.planCheckDate = moment(params.planCheckDate).format('YYYY-MM-DD');
        params.templateName = this.templateNames;
        params.templateId = this.templateIds;

        if(this.projectInfo.length > 0){
            params.projectId = this.projectInfo[0]['projectId'];
            this.projectId = this.projectInfo[0]['projectId'];
        }

        if (this.type === 'mainTask' || this.type === 'addChildTask') {
            this.request.postRequest(this.server.baseUrl +appProductUrl.addTask, params).then(res => {
                if (res.result_code === '0000') {
                    this.onSubmit.emit();
                    this.taskId = res.taskID;
                    console.log('taskData',res,',');
                }

                this.hintsService.messages(res.message, res.result_code);
                return;
            }).catch((err: any) => {
                this.hintsService.messages('error', 'error');
                return;
            });
        } else if (this.type === 'edit') {
            params.taskId = this.taskData.taskId;
            this.request.postRequest(this.server.baseUrl +appProductUrl.updateTask, params).then(res => {
                if (res.result_code === '0000') {
                    this.onSubmit.emit();
                }

                this.hintsService.messages(res.message, res.result_code);
                return;
            }).catch((err: any) => {
                this.hintsService.messages('error', 'error');
                return;
            });
        }
    }

    /**
     * 关闭弹出窗
     */
    private dismissModal() {
        this.initService._init();
        this.clear();
        $("#productTastListAdd").modal('hide');
    }

    // 分配给
    getAssignPersonsNames(names) {
        this.taskAssignUserNames = names;
        this.taskAssignPeoplesNames = this.taskAssignUserNames.split(',');
    }

    // 审核人
    getAuditPersonsNames(names) {
        this.taskAuditUserNames = names;
    }

    // 模板名称
    getTemplateNames(names) {
        this.templateNames = names;
    }

    // 模板Id
    getTemplateIds(ids) {
        this.templateIds = ids;
    }

    // 主题词表
    getThemeWordNames(names) {
        this.themeWordNames = names;
    }
    getThemeWordIds(ids) {
        this.themeWordIds = ids;
        this.taskThemeWordIds = this.themeWordIds.split(',');
    }
}

